from server.app.cloud_ide.schema.roles.request.role_create_request import RoleCreateRequest
from server.app.cloud_ide.schema.roles.request.role_update_request import RoleUpdateRequest
from server.app.cloud_ide.service.role_service import RoleService
from behave import *

from server.app.cloud_ide.service.tenant_service import TenantService

role_service = RoleService()
tenant_service = TenantService()


@step('编辑租户[{tenant_name}]下的角色[{role_name}],修改信息如下')
def 编辑租户_下的角色_修改信息如下(context, tenant_name, role_name):
    tenant = tenant_service.get_tenant_by_name(tenant_name)
    roles = role_service.get_role_list(tenant_id=tenant.id)
    role = next((x for x in roles if x.name == role_name), None)
    rs = role_service.update_role(RoleUpdateRequest(
        id=role.id,
        name=context.table[0]['name'],
        max_cpu=context.table[0]['max_cpu'],
        max_memory=context.table[0]['max_memory'],
        max_disk=context.table[0]['max_disk'],
        allow_nodes=context.table[0]['allow_nodes']
    ))
    assert rs


@step('删除租户[{tenant_name}]的以下角色')
def 删除租户_的以下角色(context, tenant_name):
    tenant = tenant_service.get_tenant_by_name(tenant_name)
    if tenant is not None:
        roles = role_service.get_role_list(tenant_id=tenant.id)
        for row in context.table:
            role = next((x for x in roles if x.name == row['name']), None)
            rs = role_service.delete_roles([str(role.id)])
            assert rs


@step('在租户下新增角色,信息如下')
def 在租户下新增角色_信息如下(context):
    for row in context.table:
        tenant = tenant_service.get_tenant_by_name(row['tenant_name'])
        rs = role_service.create_role(RoleCreateRequest(
            tenant_id=tenant.id,
            name=row['name'],
            max_cpu=row['max_cpu'],
            max_disk=row['max_disk'],
            max_memory=row['max_memory'],
            allow_nodes=row['allow_nodes']
        ))
        assert rs
